package com.ziyueyuwen.xiniao.controller.homework;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.BaseUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.homework.AnswerData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.bean.homework.ZyHomeworkRecordDO;
import com.ziyueyuwen.xiniao.bean.homework.ZySubjectQuestionDO;
import com.ziyueyuwen.xiniao.enums.MessageTypeEnum;
import com.ziyueyuwen.xiniao.enums.QuestionTypeEnum;
import com.ziyueyuwen.xiniao.service.HomeworkRecordService;
import com.ziyueyuwen.xiniao.service.LessonService;
import com.ziyueyuwen.xiniao.service.SubjectQuestionService;
import com.ziyueyuwen.xiniao.spi.QuestionTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

import static com.ziyueyuwen.xiniao.base.BaseUtil.checkParam;
import static com.ziyueyuwen.xiniao.util.ConstUtil.*;

/**
 * @author jun 2018/12/20.
 */
@Controller
@RequestMapping("/homework")
public class HomeworkController {

    @Autowired
    private SubjectQuestionService subjectQuestionService;

    @Autowired
    private HomeworkRecordService homeworkRecordService;

    @Autowired
    private LessonService lessonService;

    @RequestMapping(value = "/get_question.do", method = RequestMethod.POST)
    public void getQuestion(@RequestParam(PARAM_SUBJECT_ID) Integer subjectId,
                            @RequestParam(PARAM_HOMEWORK_INDEX) Integer homeworkIndex,
                            HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<ZySubjectQuestionDO> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取课程下的课节对应的题目");
        try {
            // check.
            checkParam(PARAM_SUBJECT_ID, subjectId);
            checkParam(PARAM_HOMEWORK_INDEX, homeworkIndex);
            // do.
            ZySubjectQuestionDO ret = subjectQuestionService.getBySubjectIdAndHomeworkIndex(subjectId, homeworkIndex);
            if (ret == null) {
                throw new Exception("题目不存在或已删除");
            }
            BaseUtil.saveSuccessMsgAndData(hrc, ret);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save_answer.do", method = RequestMethod.POST)
    public void getHomeworkRecord(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                  @RequestParam(PARAM_QUESTION_NUM) Integer questionNum,
                                  @RequestParam(PARAM_ANSWER_DATA) String answerData,
                                  HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存答案");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            checkParam(PARAM_ANSWER_DATA, answerData);
            checkParam(PARAM_QUESTION_NUM, questionNum);
            // do.
            ZyHomeworkRecordDO zyHomeworkRecord = homeworkRecordService.getById(homeworkRecordId);
            // 当前学生的验证
            if (!zyHomeworkRecord.getStudentId().equals(hrc.getUserInfo().getUserAccount())) {
                throw new Exception("作业不属于您, 保存失败!");
            }
            ZySubjectQuestionDO zySubjectQuestion = subjectQuestionService.getById(zyHomeworkRecord.getSubjectQuestionId());
            QuestionInfo questionInfo = zySubjectQuestion.getQuestionInfoList().get(questionNum - 1);
            ServiceLoader<QuestionTypeService> services = ServiceLoader.load(QuestionTypeService.class);
            for (QuestionTypeService q : services) {
                q.saveAnswer(answerData, questionNum, questionInfo, zyHomeworkRecord.getAnswerInfoList());
            }
            if (!homeworkRecordService.updateStudentAnswer(zyHomeworkRecord.getId(), zyHomeworkRecord.getAnswerInfoList())) {
                throw new Exception("保存答案入库失败!");
            }
            lessonService.studentLessonReportDataCollect(zyHomeworkRecord.getLessonId(), zyHomeworkRecord.getStudentId(), MessageTypeEnum.MESSAGE_LESSON_HOMEWORK);
            BaseUtil.saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/finish_homework.do", method = RequestMethod.POST)
    public void finishHomework(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                               HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("完成作业");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            // do.
            ZyHomeworkRecordDO zyHomeworkRecord = homeworkRecordService.getById(homeworkRecordId);
            // 当前学生的验证
            if (!zyHomeworkRecord.getStudentId().equals(hrc.getUserInfo().getUserAccount())) {
                throw new Exception("作业不属于您, 保存失败!");
            }
            initUnFinishStudentAnswer(zyHomeworkRecord);
            if (!homeworkRecordService.finisHomework(homeworkRecordId)) {
                throw new Exception("更新数据入库失败!");
            }
            lessonService.studentLessonReportDataCollect(zyHomeworkRecord.getLessonId(), zyHomeworkRecord.getStudentId(), MessageTypeEnum.MESSAGE_LESSON_HOMEWORK);
            BaseUtil.saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    private void initUnFinishStudentAnswer(ZyHomeworkRecordDO zyHomeworkRecord) throws Exception {
        ZySubjectQuestionDO zySubjectQuestion = subjectQuestionService.getById(zyHomeworkRecord.getSubjectQuestionId());
        List<QuestionInfo> questionInfoList = zySubjectQuestion.getQuestionInfoList();
        List<AnswerData> answerDataList = zyHomeworkRecord.getAnswerInfoList();
        for (int i = answerDataList.size(); i < questionInfoList.size(); i++) {
            QuestionInfo questionInfo = questionInfoList.get(i);
            int size = 1;
            if (questionInfo.getQuestionType() != QuestionTypeEnum.SUBJECTIVE) {
                size = questionInfo.getAnswerList().size();
            }
            List<String> answerData = initAnswerData(size);
            ServiceLoader<QuestionTypeService> services = ServiceLoader.load(QuestionTypeService.class);
            for (QuestionTypeService q : services) {
                q.saveAnswer(JSON.toJSONString(answerData), i + 1, questionInfo, zyHomeworkRecord.getAnswerInfoList());
            }
        }
        if (!homeworkRecordService.updateStudentAnswer(zyHomeworkRecord.getId(), answerDataList)) {
            throw new Exception("自动保存未作答题的答案入库失败!");
        }
    }

    private List<String> initAnswerData(int size) {
        List<String> answerDataList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            answerDataList.add(StringUtils.EMPTY);
        }
        return answerDataList;
    }

    @RequestMapping(value = "/list_classroom_test_question.do", method = RequestMethod.POST)
    public void listClassroomTestQuestion(@RequestParam(PARAM_EEO_CLASS_ID) Integer eeoClassId) throws Exception {
        HttpResContent<JSONObject> hrc = new HttpResContent<>("获取课中互动题目");
        // check.
        checkParam(PARAM_EEO_CLASS_ID, eeoClassId);
        // do.
        JSONObject retObj = subjectQuestionService.getClassroomTestQuestion(eeoClassId);
        hrc.printLogAndResponse(retObj);
    }

}
